/**
 * Administration utilities
 *
 * This file contains all the logic and function for the COMA adminstration pannel
 * - User management
 * - Log vieweing
 * - Initial installation
 *
 */

function showAdminPannel() {
    // Clear list and edit pannels
    $('#edit_container').fadeOut(400);
    $('#list_container').fadeIn(400);
    $('#edit_container').empty();
    $('#list_container').empty();


    // Put jquery in synchronous mode lo control loading process
    jQuery.ajaxSetup({
        async: false
    });

    // Load external HTML into container    
    $('#list_container').load('html/admin.html?t=' + new Date().getTime() + ' #container', function (response, status, xhr) {
        if (status == "error") {
            console.error('Sorry but there was an error: ' + xhr.status + " " + xhr.statusText);
            setStatus('No se encuentra el fichero HTML ./html/admin.html\': ' + xhr.status + '. ' + xhr.statusText, MESSAGE_ERROR);
        } else {
            console.log('Succesfully loaded admin.html');
        }
    });

    // Put jquery in synchronous mode lo control loading process
    jQuery.ajaxSetup({
        async: true
    });

    // Collapse edit pannel
    $('#panel_usuario').addClass('collapsing');

    // List users
    var data = database.dbSelectSynch('usuarios');
    $('#tbl_usuarios').empty();

    var table = $('<table/>');
    table.addClass('table');
    table.addClass('table-striped');

    table.append('<tr><th>Id</th><th>Username</th><th>Nombre</th><th>Rol</th><th>Administrador</th><th>Último login</th><th>&nbsp;</th></th>');
  

    for (var i = 0; i < data.length; i++) {
                var action = '<button type="button" class="btn btn-default" onclick="editUser(' + data[i].id + ')"><span class=" + glyphicon glyphicon-pencil"></span> Editar</button>';
        var nombre = (data[i].nombre == null ? '' : data[i].nombre);
        var surname = (data[i].surname == null ? '' : data[i].surname);

        var role_name = $(Business).find('BusinessRole[id="' + data[i].role + '"]').find('name').text();
        if (role_name == '')
            role_name = '(Sin informar)';
        var admin_value = (data[i].isadmin == '1' ? 'Sí' : 'No');
        var last_login = (data[i].lastlogin == null ? '(nunca)' : data[i].lastlogin);

        table.append('<tr><td>' + data[i].id + '</td><td>' + data[i].usuario + '</td><td>' + nombre + ' ' + surname + '</td><td>' + role_name + '</td><td>' + admin_value + '</td><td>' + last_login + '</td><td>' + action + '</td></tr>');

    }

    $('#tbl_usuarios').append(table);

    // Fill the Roles info
    var combo = $('#role');
    combo.empty();
    $('<option />', {
        val: '',
        text: '(Seleccione uno)'
    }).appendTo(combo);
    for (var i = 0; i < $(Business).find('BusinessRole').length; i++) {
        var rol = $(Business).find('BusinessRole')[i];
        var rol_name = $(rol).find('name').text();
        var rol_id = $(rol).attr('id');
        combo.append($('<option>').text('(' + rol_id + ') ' + rol_name).val(rol_id));
    }

    // Adjustments pannel
    if (debug)
        $('#chk_debug').prop('checked', true);
    else
        $('#chk_debug').prop('checked', false);
}



function editUser(Id) {
    // Display pannel
    $('#panel_usuario').removeClass('collapsing');

    var data = database.dbSelectSynch('usuarios', Id);

    if (data == null || data.length > 1) {
        alert('El usuario con identificador ' + Id + ' no existe');
    }

    // Display user information
    $('#id').val(data['id']);
    $('#username').val(data['usuario']);
    if (data['isadmin'] == '1') {
        $('#admin').prop('checked', true);
    } else {
        $('#admin').prop('checked', false);
    }
    $('#nombre').val(data['nombre']);
    $('#surname').val(data['surname']);
    $('#email').val(data['email']);
    $('#phone').val(data['phone']);
    $('#role').val(data['role']);
}

function createUser() {
    // Display pannel
    $('#panel_usuario').removeClass('collapsing');
    
    $('#id').val('-1');
    $('#username').val('username');
    $('#admin').prop('checked', false);
    $('#nombre').val('Nuevo Nombre');
    $('#surname').val('Nuevo apellido');
    $('#email').val('Nuevo email');
    $('#phone').val('000 00 00 00');
}

function saveUser() {
    // Check password change
    if ($('#password').val() != '') {
        if ($('#password').val() != $('#password_repeat').val()) {
            alert('Las contraseñas han de ser iguales');
            return;
        }
    }
    var admin_value;
    if ($('#admin').is(':checked'))
        admin_value = 1;
    else
        admin_value = 0;

    var user = new User($('#id').val(), $('#username').val().toLowerCase(), encriptarPassword($('#password').val()), $('#nombre').val(), $('#surname').val(), $('#role').val(), admin_value);

    if ($('#password').val() == '')
        delete user.password;

    database.dbUpdateSynch('usuarios', user);
    // Refresh
    showAdminPannel();
}

function cancelEditUser() {
    showAdminPannel();
}

function encriptarPassword(password) {
    var hash = CryptoJS.MD5(password);
    return hash.toString(CryptoJS.enc.Base64);
}